import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import {AppState} from '@store/index'

// 定黑名单 不需要携带token的接口
const BlackList = ['login','sendMsgCode'];
// 自定义 baseQuery，全局注入 token 
const baseQuery = fetchBaseQuery({
  baseUrl: process.env.REACT_APP_BASE_URL, 
  prepareHeaders: (headers, { getState, endpoint}) => {
    console.log(endpoint,'--->>')
    // 判断当前请求的接口是否在黑名单内
    const isIn = Array.isArray(BlackList) && BlackList.includes(endpoint);
    if (!isIn) {
      console.log(' 需要注入token')
      //不是请求的登录接口 需要注入token
      const state = getState() as AppState;
      const token = state.credentialsReducer.token;
      if (token) {
        headers.set('Authorization', `Bearer ${token}`);
      }
    }
    return headers;
  },
});
// 创建了一个全局的API状态切片
const apiService = createApi({
  reducerPath: "apiReducer",
  baseQuery,
  endpoints: () => ({}),
});

export default apiService;